package repository;

import java.math.BigDecimal;

import models.Actor;
import models.Transaction;
import prefix.util.JPAUtil;
import prefix.util.jpaQueryfier.JpaQueryfier;
import service.ActorService;
import service.impl.ActorServiceImpl;

public class ActorRepository extends AbstractRepository {

    public static ActorService getActorServiceById(Integer aid) {

        Actor actor = JPAUtil.em().find(Actor.class, aid);

        if (actor != null) {
            return new ActorServiceImpl(actor);
        }
        return null;
    }

    public static ActorService getActorServiceByEmail(final String email) {

        Actor actor = getSingleByProperty(Actor.class, "email", email, null);

        if (actor != null) {
            System.out.println(actor.getUsername());
            return new ActorServiceImpl(actor);
        }
        return null;

    }

    private final static String getPendingHoldBalanceSQL = " select IFNULL(sum(amount), 0) from transaction where status in  "
            + buildInList(Transaction.Status.PENDING, Transaction.Status.IN_REVIEW)
            + " and type in "
            + buildInList(Transaction.Type.T3_PUSH_FUNDS_TO_BORROWER_BANK, Transaction.Type.T4_BORROWER_PAY_ORIG_FEE,
                    Transaction.Type.T5_BORROWER_PAY_MANAGEMENT_FEE, Transaction.Type.T6_LENDER_PAY_SERVICE_FEE,
                    Transaction.Type.T8_BORROWER_MTHLY_PAY_TO_LENDER) + " and from_aid = :from_aid";

    public static Double getPendingHoldBalance(Integer aid) {
        return (Double) new JpaQueryfier(getPendingHoldBalanceSQL, JPAUtil.em()).with(aid).queryfyNative(null)
                .getSingleResult();
    }

    private final static String getSumTransactions = " select sum(trans.AMOUNT) from transaction trans "
            + " join actor ON actor.ID = trans.TO_AID" + " where trans.TYPE =:type" + " and trans.status = 1"
            + " and actor.id = :aid";

    public final static Double getSumOfTransactions(Transaction.Type type, Integer aid) {
        return (Double) new JpaQueryfier(getSumTransactions, JPAUtil.em()).with(type.ordinal()).with(aid)
                .queryfyNative(null).getSingleResult();
    }

    public ActorRepository() {
        super();
        // TODO Auto-generated constructor stub
    }

}
